<template>
  <div>
    <shopping-car :goodList="goodList">
      <template #head>
        <th><input type="checkbox" v-model="all" /> <span>全选</span></th>
        <th>名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>总价</th>
        <th>操作</th>
      </template>
      <template #main="{ item, index }">
        <td><input type="checkbox" v-model="item.checked" /></td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>
          <button @click="even(index, '0')">-</button>{{ item.num
          }}<button @click="even(index, '1')">+</button>
        </td>
        <td>{{ item.price * item.num }}</td>
        <td><button @click="del(index)">删除</button></td>
      </template>
      <template #foot>
        <td>合计:{{ total }}</td>
        <td colspan="5"></td>
      </template>
    </shopping-car>
  </div>
</template>

<script>
import ShoppingCar from "./components/shopping-car";
export default {
  data() {
    return {
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  components: {
    ShoppingCar,
  },
  methods: {
    even(id, flag) {
      if (flag === "1") {
        this.goodList[id].num++;
      } else {
        if (this.goodList[id].num > 0) {
          this.goodList[id].num--;
        } else {
          this.goodList[id].num = 0;
        }
      }
    },

    del(id) {
      this.goodList.splice(id, 1);
    },
  },
  computed: {
    total() {
      return this.goodList.reduce(
        (sum, item) => (sum += item.price * item.num),
        0
      );
    },

    all: {
      get() {
        return this.goodList.every((item) => item.checked === true);
      },
      set(value) {
        return this.goodList.forEach((item) => (item.checked = value));
      },
    },
  },
};
</script>

<style></style>
